﻿using CMS.Mode;
using DBMode;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CMS.ViewModels
{
    public class RecordViewModel:BindableBase
    {
        private readonly IDialogService dialogService;
        private readonly IMethods<Record> recordMethods;

        public RecordViewModel(IDialogService dialogService,IMethods<Record> recordMethods)
        {
            this.dialogService = dialogService;
            this.recordMethods = recordMethods;
            Refresh();
        }
        private List<Record> records;
       

        public List<Record> Records
        {
			get { return records; }
			set { records = value; RaisePropertyChanged(); }
		}


        public DelegateCommand AddRecordCommand { get { return new DelegateCommand(AddRecord); } }
		public DelegateCommand<object> EditCommand { get { return new DelegateCommand<object>(Edit); } }

        private void Edit(object obj)
        {
            if (obj is Record record)
            {
                if (record.Index == 0) record.Type = false; 
                if (record.Index == 1) record.Type = true; 
                int a = recordMethods.Update(record);
                if (a != 0) MessageBox.Show("操作成功");
                else
                    MessageBox.Show("操作失败");
            }
        }

        private void AddRecord()
        {
            IDialogParameters dialogParameters = new DialogParameters();
            dialogParameters.Add("add", null);
            dialogService.ShowDialog("AddRecordView", dialogParameters,callback =>
            {
                if (callback.Result == ButtonResult.OK)
                { Refresh(); }
            });
        }

        private void Refresh()
        {
            Records = recordMethods.Query();
            Records.ForEach(i => {
                if (i.Type == true) i.Index = 1;
                if (i.Type == false) i.Index = 0;
            }
                
                );
        }
    }
}
